<!--
 * @author: Goalias
 * @since: 2025-01-03
-->
<script setup lang="ts">
import { reactive, ref, onMounted, watch, nextTick } from 'vue'
import type { FormInstance, FormRules, UploadInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import TextEditor from '@/components/TextEditor.vue'
import { DocumentAdd, RefreshRight, Delete } from '@element-plus/icons-vue'
import { categoryApi } from '@/apis/CategoryApi'
import { tagApi } from '@/apis/TagApi'
import { Category } from '@/apis/types/Category'
import { articleApi } from '@/apis/ArticleApi'
import type { UploadProps } from 'element-plus'
import { Tag } from '@/apis/types/Tag'
import { Article } from '@/apis/types/Article'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/userStore'
import PulsatingButton from '@/components/ui/pulsating-button';
import { fileApi } from '@/apis/FileApi'

const userStore = useUserStore()
const token = userStore.userInfo?.goaliasToken

const form = ref<Article>({
  title: '',
  category: '',
  tagName: '',
  content: '',
  summary: '',
  thumbnail: '',
  isDraft: false,
  isTop: false
});
const thumbnailUrl = ref<string>()

const editorRef = ref<InstanceType<typeof TextEditor>>()
const rules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入博客标题', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度应在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择博客分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入博客内容', trigger: 'blur' }
  ],
  summary: [
    { max: 1024, message: '摘要长度不能超过 1024 个字符', trigger: 'blur' }
  ]
})

const categories = ref<Category[]>([])
const categoryId = ref<number>()

const formRef = ref<FormInstance>()

// 添加标签数据的响应式引用
const tags = ref<Tag[]>([])

// 添加上传组件的ref
const uploadRef = ref<UploadInstance>()

// 获取分类列表
const loadCategories = async () => {
  try {
    const response = await categoryApi.getList()
    categories.value = response.data
  } catch (error) {
    ElMessage.error('获取分类列表失败')
  }
}

const initializeArticle = () => {
    const articleJson = localStorage.getItem('editArticle')
    if (articleJson) {
        try {
            const articleDetail = JSON.parse(articleJson)
            // 填充表单数据
            form.value = {
                id: articleDetail.id,
                title: articleDetail.title,
                category: articleDetail.categoryName,
                tagName: articleDetail.tagName,
                content: articleDetail.content,
                summary: articleDetail.summary,
                thumbnail: articleDetail.thumbnail ? articleDetail.thumbnail.split('goalias-blog/')[1] : '',
                isDraft: articleDetail.status,
                isTop: articleDetail.isTop
            }
            
            // 设置缩略图URL
            if (articleDetail.thumbnail) {
                thumbnailUrl.value = articleDetail.thumbnail
            }
            
            // 设置富文本编辑器的内容
            nextTick(() => {
                if (editorRef.value) {
                    editorRef.value.setHtml(articleDetail.content)
                }
            })

            // 清除临时存储的数据
            localStorage.removeItem('editArticle')
        } catch (error) {
            ElMessage.error('初始化文章数据失败')
        }
    }
}

onMounted(() => {
    loadCategories()
    initializeArticle() // 确保在加载分类后初始化文章
    // 监听分类变化，获取对应的标签
    watch(() => form.value.category, async (newCategory) => {
        if (!newCategory) {
            tags.value = []
            form.value.tagName = ''
            return
        }

        // 获取选中分类的名称
        const selectedCategory = categories.value.find(c => c.name === newCategory)
        try {
            categoryId.value = selectedCategory?.id
            const response = await tagApi.getTags(categoryId.value)
            tags.value = response.data
        } catch (error) {
            ElMessage.error('获取标签列表失败')
        }
    })
})

const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  // 获取富文本编辑器的内容
  form.value.content = editorRef.value?.getHtml() || ''

  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const response = await articleApi.addArticle(form.value)
        if (response.data) {
          form.value.id = response.data
          ElMessage.success('提交成功！')
        }
      } catch (error) {
        ElMessage.error('提交失败')
      }
    } else {
      ElMessage.error('发布内容验证失败，请检查输入！')
    }
  })
}

const deleteUploadedFile = async () => {
  if (form.value.thumbnail) {
    try {
      await fileApi.deleteObject([form.value.thumbnail])
      form.value.thumbnail = ''
      thumbnailUrl.value = ''
      // 重置上传组件状态
      uploadRef.value?.clearFiles()
    } catch (error) {
      ElMessage.error('删除文件失败')
    }
  }
}

// 修改重置表单的方法
const resetForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  // 先删除已上传的缩略图
  if (form.value.thumbnail && form.value.thumbnail !== '') {
    await deleteUploadedFile()
  }
  formEl.resetFields()
  form.value.id = undefined
}

// 添加文件移除的处理方法
const handleRemove = async () => {
  await deleteUploadedFile()
}

const handleThumbnailSuccess = (response: any) => {
  if (response.code === 200) {
    form.value.thumbnail = response.data.fileName
    thumbnailUrl.value = response.data.fileUrl
  } else {
    resetForm(formRef.value)
    thumbnailUrl.value = ''
    ElMessage.error(response.message || '上传封面图片失败')
  }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size > 50 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过50MB');
    return false
  }
  return true
}

const handleThumbnailError = (error: any) => {
  // 重置文件状态
  form.value.thumbnail = ''
  thumbnailUrl.value = ''
  ElMessage.error(error.message || '上传封面图片失败')
}

</script>

<template>
  <div class="article-container">
    <div class="article">
      <h2 class="form-title">📜 创建博客 📜</h2>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px" class="article-form">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入文章标题" :maxlength="50" show-word-limit />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="文章分类" prop="category">
              <el-select v-model="form.category" placeholder="请选择或输入文章分类" class="w-full" filterable allow-create
                clearable>
                <el-option v-for="item in categories" :key="item.id" :label="item.name" :value="item.name" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="文章标签" prop="tagName">
              <el-select v-model="form.tagName" placeholder="请先选择文章分类" class="w-full" filterable allow-create
                :disabled="!form.category">
                <el-option v-for="tag in tags" :key="tag.id" :label="tag.name" :value="tag.name" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="文章内容" prop="content" class="editor-container">
          <TextEditor ref="editorRef" :value="form.content" :category-id="0" />
        </el-form-item>

        <el-form-item label="文章摘要" prop="summary">
          <el-input v-model="form.summary" type="textarea" :rows="3" placeholder="请输入文章摘要" :maxlength="1024"
            show-word-limit />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="封面缩略图" prop="thumbnail">
              <el-upload 
                ref="uploadRef"
                class="thumbnail-uploader" 
                :action="`/api/ability/file/upload?categoryId=${categoryId || -1}`"
                :headers="{ 'Goalias-Token': 'Bearer ' + token }" 
                :show-file-list="false"
                :before-upload="beforeAvatarUpload" 
                :on-success="handleThumbnailSuccess"
                :on-error="handleThumbnailError"
                :on-remove="handleRemove"
                :limit="1" 
                list-type="picture" 
                drag
              >
                <template v-if="thumbnailUrl">
                  <div class="thumbnail-wrapper">
                    <img :src="thumbnailUrl" class="thumbnail" />
                    <div class="thumbnail-actions">
                      <el-button 
                        type="danger" 
                        size="large"
                        circle
                        @click.stop="handleRemove"
                      >
                        <el-icon :size="20">
                          <Delete />
                        </el-icon>
                      </el-button>
                    </div>
                  </div>
                </template>
                <el-icon v-else class="thumbnail-uploader-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="保存为草稿?" prop="isDraft">
              <el-switch v-model="form.isDraft" active-text="是" inactive-text="否" />
            </el-form-item>
            <el-form-item label="保持置顶?" prop="isTop">
              <el-switch v-model="form.isTop" active-text="是" inactive-text="否" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item class="form-buttons">
          <PulsatingButton 
            type="button"
            pulseColor="var(--theme-color)" 
            duration="2s" 
            class="submit-button"
            @click="onSubmit(formRef)"
          >
            <el-icon>
              <DocumentAdd />
            </el-icon>
            发布文章
          </PulsatingButton>
          <PulsatingButton 
            type="button"
            pulseColor="var(--theme-color)" 
            duration="2s" 
            class="submit-button"
            @click="resetForm(formRef)"
          >
            <el-icon>
              <RefreshRight />
            </el-icon>
            重置
          </PulsatingButton>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.article-container {
  min-height: 100vh;
  background-color: #f5f7fa;
  padding: 3vw
}

.article {
  background-color: #fff;
  padding: 3vw;
  border-radius: 5vw;
  box-shadow: -10px -10px 3vw rgba(6, 218, 229, 0.8), 10px 10px 3vw rgba(229, 6, 218, 0.8);
  transition: all 0.3s ease;
  background: rgba(236, 222, 244, 0.816);
}

.form-title {
  margin-bottom: 5vh;
  color: #303133;
  font-size: 2vw;
  text-align: center;
  font-weight: 600;
  background: linear-gradient(135deg, #409EFF 0%, #ff80f0 100%);
  border-radius: 3vw;
  color: #f2c05d;
}

.article-form {
  max-width: 70vw;
  margin: 0 auto;
}

.editor-container {
  margin-bottom: 3vw;
}


.thumbnail-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 1.5vw;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: border-color 0.3s;
}

.thumbnail-uploader:hover {
  border-color: #409EFF;
}

.thumbnail-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 10vw;
  height: 10vw;
  text-align: center;
  line-height: 10vw;
}

.thumbnail-wrapper {
  position: relative;
  width: 10vw;
  height: 10vw;
}

.thumbnail-actions {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: none;
  padding: 1vw;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  transition: all 0.3s ease;
}

.thumbnail-wrapper:hover .thumbnail-actions {
  display: block;
}

.thumbnail-actions .el-button:hover {
  transform: scale(1.1);
  box-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
}

.thumbnail {
  width: 10vw;
  height: 10vw;
  display: block;
  object-fit: cover;
}
.w-full {
  width: 100%;
}

.form-buttons {
  margin-top: 2vw;
}

.submit-button {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 5vw;
  margin-left: 5vw;
  font-size: 20px;
}

:deep(.el-form-item__label) {
  background: linear-gradient(135deg, #409EFF 0%, #ff80f0 100%);
  border-radius: 2vw;
  margin-right: 1vw;
  color: #fff;
}

:deep(.el-input__wrapper),
:deep(.el-textarea__inner) {
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover),
:deep(.el-textarea__inner:hover) {
  box-shadow: 0 0 0 1px #409EFF inset;
}

/* 优化表单布局 */
:deep(.el-form-item) {
  margin-bottom: 2vw;
}
</style>